/*
 * @Author: 张笑天
 * @Date: 2018-03-07 17:09:16
 * @Last Modified by: lyuan2018
 * @Last Modified time: 2020-08-13 11:45:46
 * 两栏模式
 */
import React from 'react';
import { routerShape } from 'react-router';
import { inject, observer } from 'mobx-react';
import { Spin, Pagination, Tooltip } from 'antd';
import classNames from 'classnames';
import {
  WeaErrorPage,
  WeaTools,
  WeaNewScroll,
  WeaCheckbox,
  WeaTag,
  WeaAlertPage,
  WeaLocaleProvider,
  WeaAvatar,
} from 'ecCom';

import { PopoverTodo } from '../com';
import { getFlagCls } from '../../util/index';
import WeaCircleImage from '../../public/wea-circle-image';

const getLabel = WeaLocaleProvider.getLabel;

const checkKeyInCols = (datas, key) =>
  datas.filter(d => d.dataIndex === key).length;

const { tryCatch } = WeaTools;
const store = ['routing', 'emailMainStore'];

@tryCatch(
  React,
  props => (
    <WeaErrorPage
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaErrorPage@x4gxse`}
      msg={
        props.error ||
        getLabel(186, '对不起，该页面异常，请联系管理员！', 'error')
      }
    />
  ),
  { error: '' },
)
@inject(...store)
@observer
class List extends React.Component {
  static displayName = 'LeftList';
  static contextTypes = {
    router: routerShape,
  };
  constructor(props) {
    super(props);
    this.prefixClass = 'wea-email-list-left-list';
    this.timer = null;
  }
  componentDidMount() {}
  componentWillReceiveProps() {}
  componentWillUnmount() {
    clearTimeout(this.timer);
  }

  // 两栏模式下的打开
  onEmailOpen(type, id, subject) {
    const { router } = this.context;
    const {
      emailMainStore: { addViewStore },
      onSetReadStatus,
    } = this.props;
    typeof onSetReadStatus === 'function' &&
      onSetReadStatus([id], 1, true, true, '', () => {
        addViewStore(id, type);
        subject = subject.replace(/%/g, '/%25');
        type === 'inTab' &&
          router.push(
            `main/email/view?id=${id}&title=${
              subject || getLabel(384186, '查看邮件')
            }`,
          );
      });
  }
  hide = () => {
    const { dataSource = [] } = this.props;
    dataSource.forEach(({ waitdeal, id }) => {
      waitdeal && this.refs[`todo${id}`].hide();
    });
  };

  // 邮件识别发票
  emailOcrInvoice(params) {
    const { emailOcrInvoice } = this.props;
    typeof emailOcrInvoice === 'function' && emailOcrInvoice(params);
  }

  // get
  getItem = (
    columns,
    {
      flagSpan: { className, labelId, timingDate },
      status,
      sendfromSpan: { imageUrl, realName, title, userId },
      toSpan: { realName: _realName, title: _title },
      id,
      subject,
      hasAttachment,
      senddateSpan,
      labels,
      starred,
      waitdeal,
      content,
      waitdealBean,
      isInternal,
      priority,
      belongtoType,
      belongtoInfo,
      folderid,
      emailOcrInvoiceStatus,
    },
    { selectedRowKeys, onChange },
    datas,
    viewId,
  ) => {
    let listTitle =
      className === 'timingdate' && timingDate
        ? getLabel(509534, '邮件将于{date}发送').replace('{date}', timingDate)
        : labelId;
    let headerProps = { name: realName, url: imageUrl, userId };
    let headerFlag =
      checkKeyInCols(columns, 'sendfromSpan') === 1 && isInternal === 1;
    const { onSetReadStatus } = this.props;
    return (
      <div
        className={`${this.prefixClass}-item ${
          belongtoType === '' ? '' : 'belongtoType'
        }`}
        style={viewId === id ? { backgroundColor: '#e9f7ff' } : null}
      >
        <div className={`${this.prefixClass}-item-left`}>
          <WeaCheckbox
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaCheckbox@5uwi9b`}
            value={selectedRowKeys.indexOf(id) < 0 ? '0' : '1'}
            onChange={(v) => {
              let sKeys = [];
              let _datas = [];
              if (v === '1') {
                sKeys = selectedRowKeys.concat([id]);
                _datas = datas.filter(
                  d => sKeys.indexOf(d.id) >= 0 || id === d.id,
                );
              } else {
                sKeys = selectedRowKeys.filter(k => k !== id);
                _datas = datas.filter(d => sKeys.indexOf(d.id) >= 0);
              }
              typeof onChange === 'function' && onChange(sKeys, _datas);
            }}
          />
          <div className="account-type">
            {belongtoType !== '' ? (
              <Tooltip
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_Tooltip@dqrfbf`}
                title={`${belongtoInfo.name}|${belongtoInfo.department}|${belongtoInfo.job}`}
                placement="right"
              >
                {belongtoType * 1 === 1 ? (
                  <span
                    className="icon-coms02-Main-account-number"
                    style={{ color: '#F5A623', fontSize: 17 }}
                  />
                ) : belongtoType * 1 === 2 ? (
                  <span
                    className="icon-coms02-Secondary-account-number"
                    style={{ color: 'grey', fontSize: 17 }}
                  />
                ) : (
                  ''
                )}
              </Tooltip>
            ) : (
              ''
            )}
          </div>
          <i className={getFlagCls(className)} title={listTitle} />
          {priority === '1' ? (
            <span
              title={getLabel(2087, '紧急')}
              className={`${this.prefixClass}-item-left-priority`}
            >
              !
            </span>
          ) : null}
          {headerFlag ? (
            <div className="wea-email-avatar">
              <WeaAvatar
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaAvatar@bur585`}
                {...headerProps}
                style={{ width: 40, height: 40 }}
              />
            </div>
          ) : null}
          {!headerFlag ? (
            <div className={`wea-email-avatar ${this.prefixClass}-item-avatar`}>
              <WeaCircleImage
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaCircleImage@affmtp`}
                diameter={40}
                src={imageUrl || ''}
                name={realName || _realName || ''}
              />
            </div>
          ) : null}
        </div>
        <div
          className={`${this.prefixClass}-item-mid`}
          onClick={() => {
            clearTimeout(this.timer);
            this.timer = setTimeout(
              () =>
                (this.props.modName === 'draft' || folderid === '-2'
                  ? onSetReadStatus([id], 1, true, true, '', () => {
                      this.context.router.push({
                        pathname: 'main/email/new',
                        query: { isInternal, id, flag: 4 },
                      });
                    })
                  : this.onEmailOpen('inList', id, subject, status)),
              200,
            );
          }}
          onDoubleClick={() => {
            clearTimeout(this.timer);
            this.timer = setTimeout(
              () =>
                (this.props.modName === 'draft' || folderid === '-2'
                  ? onSetReadStatus([id], 1, true, true, '', () => {
                      this.context.router.push({
                        pathname: 'main/email/new',
                        query: { isInternal, id, flag: 4 },
                      });
                    })
                  : this.onEmailOpen('inTab', id, subject, status)),
              200,
            );
          }}
        >
          <p>
            <a
              title={checkKeyInCols(columns, 'sendfromSpan') ? title : _title}
              style={
                className === 'Ru' || status === 0 ? { fontWeight: 600 } : null
              }
            >
              {checkKeyInCols(columns, 'sendfromSpan') ? realName : _realName}
            </a>
            <i className={hasAttachment ? getFlagCls('file') : ''} />
          </p>
          <p>
            {/* 发票识别状态 */}
            {emailOcrInvoiceStatus && (
              <i
                title={
                  emailOcrInvoiceStatus === '1'
                    ? '发票已识别'
                    : '发票识别失败，点击可以再次识别。'
                }
                style={
                  emailOcrInvoiceStatus === '1'
                    ? {
                        color: '#1BDD3F',
                        'font-size': '14px',
                        position: 'relative',
                        top: 1,
                        paddingRight: '3px',
                      }
                    : {
                        color: '#F72B2B',
                        'font-size': '14px',
                        position: 'relative',
                        top: 1,
                        paddingRight: '3px',
                      }
                }
                className={
                  emailOcrInvoiceStatus === '1'
                    ? getFlagCls('invoice_right')
                    : getFlagCls('invoice_wrong')
                }
                onClick={(e) => {
                  if (emailOcrInvoiceStatus === '0') {
                    this.emailOcrInvoice({ mailid: id });
                    e.stopPropagation && e.stopPropagation();
                    e.preventDefault && e.preventDefault();
                    e.nativeEvent && e.nativeEvent.preventDefault();
                  }
                }}
              />
            )}

            <span
              title={subject}
              style={
                className === 'Ru' || status === 0 ? { fontWeight: 600 } : null
              }
              dangerouslySetInnerHTML={{ __html: subject }}
            />
          </p>
          <p style={{ color: '#a0a0a0', 'font-size': '12px' }}>{content}</p>
          {/* eslint-disable */}
          <p
            onClick={(e) => {
              e.stopPropagation && e.stopPropagation();
              e.preventDefault && e.preventDefault();
              e.nativeEvent && e.nativeEvent.preventDefault();
            }}
          >
            {/* eslint-enable */}
            {labels.map(({ color, name, id: tagId }) => (
              <WeaTag
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaTag@w62e60@${tagId}`}
                closable
                key={tagId}
                color={color}
                title={name}
                style={{ margin: '5px 10px 0 0' }}
                onClose={(e) => {
                  e.stopPropagation && e.stopPropagation();
                  e.preventDefault && e.preventDefault();
                  e.nativeEvent && e.nativeEvent.preventDefault();
                  this.props.onSetTag([id], tagId, 'removeLabel');
                }}
              >
                {name}
              </WeaTag>
            ))}
          </p>
        </div>
        <div className={`${this.prefixClass}-item-waitdeal`}>
          {waitdeal ? (
            <PopoverTodo
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_PopoverTodo@utibqh`}
              ref={`todo${id}`}
              data={waitdealBean}
              onTodoClick={p =>
                this.props.onTodoClick([id], { ...waitdealBean, ...p })
              }
              onTodoComplete={() => this.props.onTodoComplete([id])}
            >
              <span title={getLabel(384239, '查看待办信息')}>
                <i className={getFlagCls('agency', 'n')} />
              </span>
            </PopoverTodo>
          ) : (
            <i
              className={getFlagCls('agency', 'o')}
              title={getLabel(384240, '设置待办')}
              onClick={() => this.props.onTodoClick([id], waitdealBean)}
            />
          )}
        </div>
        <div
          className={`${this.prefixClass}-item-date`}
          dangerouslySetInnerHTML={{ __html: senddateSpan }}
        />
        <div
          className={classNames({
            [`${this.prefixClass}-item-right`]: true,
            [`${this.prefixClass}-item-right-fav`]: !starred,
          })}
        >
          <i
            className={getFlagCls('fav', starred ? 'n' : 'o')}
            title={
              starred
                ? getLabel(81297, '取消星标')
                : getLabel(384242, '标记星标')
            }
            onClick={() => this.props.onCollect([id], starred ? 0 : 1)}
          />
        </div>
      </div>
    );
  };
  getAlertPage = () => (
    <WeaAlertPage
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaAlertPage@26cmpi`}
      icon={<i className="icon-coms-NoData" style={{ color: '#999' }} />}
      iconSize={40}
    >
      <div style={{ color: '#999', marginTop: 16, fontSize: 14 }}>
        {getLabel(83553, '暂无数据')}
      </div>
    </WeaAlertPage>
  );
  handleScroll = () => {
    let toptab = document.getElementsByClassName('wea-email-list-left-list')[0];

    if (this.refs.scroll.getScrollTop() > 0) {
      toptab.className = 'wea-email-list-left-list scroll';
    } else {
      toptab.className = 'wea-email-list-left-list';
    }
  };
  scrollToTop = () => {
    this.refs.scroll.scrollerToTop();
  };
  render() {
    const {
      loading,
      dataSource = [],
      rowSelection,
      pagination,
      columns,
      emailMainStore: { viewId },
    } = this.props;
    return (
      <div className={this.prefixClass}>
        <Spin
          ecId={`${(this && this.props && this.props.ecId) || ''}_Spin@v66cs3`}
          spinning={loading}
        >
          <WeaNewScroll
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaNewScroll@drnpa6`}
            ref="scroll"
            height="100%"
            onScroll={this.handleScroll}
          >
            {dataSource.length === 0 && !loading
              ? this.getAlertPage()
              : dataSource.map(data =>
                  this.getItem(columns, data, rowSelection, dataSource, viewId),
                )}
          </WeaNewScroll>
          <div className={`${this.prefixClass}-pagination`}>
            <Pagination
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Pagination@l4vl6j`}
              {...pagination}
              size="small" /* simple */
            />
          </div>
        </Spin>
      </div>
    );
  }
}

export default List;
